package reflect;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

/**
 * @author wangyingjie
 * @date
 * @remark
 */
public class URLClassLoaderDemo {

    private Connection connection;

    /**
     * 测试URLClassLoader加载mysql驱动
     * @param url
     * @param user
     * @param password
     * @return
     * @throws Exception
     */
    public Connection getConnection(String url,String user,String password) throws Exception {
        //file:说明当前路径下的mysql连接jar包，也可以用http:前缀，表示HTTP联网访问获取资源，或用ftp:
        URL[] urls = {new URL("file:mysql-connector-java-3.1.10-bin.jar")};
        URLClassLoader urlClassLoader = new URLClassLoader(urls);
        //获取urlClassLoader之后可以直接加载指定类，并创建实例
        Driver driver= (Driver) urlClassLoader.loadClass("com.mysql.jdbc.driver").newInstance();
        Properties properties = new Properties();
        properties.setProperty("user",user);
        properties.setProperty("password",password);
        Connection conn = driver.connect(url, properties);
        return conn;
    }
}
